package models

import (
	"errors"
	"time"
	_ "time"

	orm "go-papers/database"
	"go-papers/tools"
)

type MemberRegister struct {
	NickName string `json:"nickName" gorm:"-"` // 昵称
	Code     string `json:"code" gorm:"-"`     // 头像地址
	Password string `json:"password" gorm:"-"` // 密码
	Phone    string `json:"phone" gorm:"-"`    // 手机号
	OpenId   string `json:"openId" gorm:"-"`   // 手机号
	MomCode  string `json:"momCode" gorm:"-"`  // 手机号
}

func (MemberRegister) TableName() string {
	return "member"
}

// 创建Member
func (e *MemberRegister) Create() (Member, error) {
	var doc Member
	table := orm.Eloquent.Table(e.TableName()).Where("account_name = ?", e.Phone)
	//判断手机号是否已经 注册
	if err := table.First(&doc).Error; err == nil {
		er := errors.New("当前手机号已经注册")
		return doc, er
	}

	//密码加密
	doc.Password = e.Password
	if err := doc.Encrypt(); err != nil {
		return doc, err
	}

	noeTime := time.Now().Format("2006-01-02 15:04:05")
	//注册 创建
	var mr MemberRegisterInfo
	mr.MemberCode = tools.GetMemberCode()
	mr.NickName = e.NickName
	mr.RealName = e.NickName
	mr.Phone = e.Phone
	mr.AccountName = e.Phone
	mr.WxOpenid = e.OpenId
	mr.Password = doc.Password
	mr.RegisterTime = noeTime
	mr.ActiveTime = noeTime
	mr.CreatedAt = noeTime
	//返回
	result, err := doc.Register(mr)
	if err != nil {
		return doc, err
	}

	//记录log
	var memerlog MemberLog
	memerlog.LogMemberId = result.MemberId
	memerlog.LogMemerName = result.NickName
	memerlog.LogName = "用户注册"
	memerlog.CreatedAt = noeTime
	memerlog.UpdatedAt = noeTime
	memerlog.LogInfo = "注册手机号" + e.Phone + "；注册微信OpenId：" + e.OpenId + "/" + e.Password
	_, _ = memerlog.Create()

	if e.OpenId != "" {
		var thirdUser ThirdUser
		er := orm.Eloquent.Table("third_user").Where("thrid_open_id = ? ", e.OpenId).Find(&thirdUser).Error
		if er != nil && thirdUser.ThridUserId > 0 {
			var memberThird MemberThirdInfo
			//根据 第三方id 查询是否有 关联 用户od
			_, _ = memberThird.InsertUpdate(thirdUser.ThridUserId, result.MemberId)
		}
	}
	return result, nil
}
